'use strict';

var koa = require('koa'),
  staticServer = require('koa-static'),
  // bunyan = require('koa-bunyan'),
  koaBunyanLogger = require('koa-bunyan-logger'),
  gzip = require('koa-gzip'),
  json = require('koa-json'),
  bodyParser = require('koa-bodyparser'),
  liveReload = require('koa-livereload'),
  session = require('koa-session'),
  views = require('co-views'),
  koaXml = require('koa-xml'),
  socketIo = require('socket.io'),
  debug = require('debug'),
  log = debug('yozh:log'),
  error = debug('yozh:error'),
  verbose = debug('yozh:verbose'),
  logger = require('./config/logger'),
  config = require('./config/config'),
  tools = require('./lib/tools'),
  cache = require('./lib/cache')(config.urlCache),
  tokenCache = require('./lib/cache')(config.tokenCache),
  requestCache = require('./middlewares/request_cache'),
  responseCache = require('./middlewares/response_cache'),
  mySocket = require('./config/my_socket')({socketIo: socketIo}),
  redirectSSL = require('./middlewares/redirect_ssl'),
  token = require('./middlewares/token'),
  permission = require('./middlewares/permission'),
  myQuery = require('./middlewares/my_query');

var app = module.exports = koa();

var render = views('views/');

/*app.use(bunyan(logger, {
  level: 'debug',
  timeLimit: 120
}));*/

// redirect https server
app.use(redirectSSL({port: 3001}));

// log middleware;
// app.use(koaBunyanLogger());
app.use(koaBunyanLogger(logger));

// request time middleware;
app.use(function *(next) {
  var start = new Date();
  yield next;
  var ms = new Date() - start;
  // this.log.info('%s request from %s for %s?%s, used time: %d ms',
  //   this.request.method, this.request.ip, this.path, this.querystring, ms);
  verbose(
    this.request.method,
    ' remoteAddress: ',
    this.req.connection.remoteAddress,
    ' x-forwarded-for: ',
    this.request.headers['x-forwarded-for'],
    ' x-real-ip: ',
    this.request.headers['x-real-ip'],
    ' request from: ',
    this.request.ip,
    ' with path: ',
    this.path,
    ' query string: ',
    this.querystring,
    ' used time: ',
    ms,
    ' ms.'
  );
});

app.keys = ['youzhe'];

// authorization middleware;
app.use(token({cache: tokenCache}));
app.use(permission());

// middleware lib chain;
app.use(gzip())
  .use(json())
  // .use(koaXml(config.koaxml))
  .use(session(app))
  // .use(liveReload())
  .use(bodyParser())
  /*.use(staticServer('../youzhe-web/app'))*/;

// request cache middleware;
// app.use(requestCache({cache: cache}));

// init Robute;
app.use(require('./middlewares/my_mw_rob')({
  wechatCtrl: require('./modules/wechat/wechat.controller')
}));

// querystring middleware;
require('koa-qs')(app);

// my custom querystring middleware;
app.use(myQuery({tools: tools}));

// check update time middleware;
// app.use(function *(next) {
//   var method = this.request.method;
// });

// router middleware;
require('./config/routes')(app);

// set response Cache-Control middleware;
// app.use(responseCache({cache: cache}));

// app.listen(3000, function(err) {
  // log('listening on port 3000');
// });

var httpServer = require('http').Server(app.callback());
// init socket io
mySocket.init(httpServer);
httpServer.listen(3080);

var httpsServer = require('https').Server(config.serverKey, app.callback());
// init socket io
mySocket.init(httpsServer);

httpsServer.listen(3443);
log('server started.');
